import Taro, { Component } from "@tarojs/taro";
import { AtSwipeAction,AtProgress, AtCheckbox } from "taro-ui";
import { View } from "@tarojs/components";
import { connect } from "@tarojs/redux";
import dayjs from 'dayjs'
import Immutable from 'immutable'

import { onCheckTodayPlan } from "../../actions/checkPlan";
import {serverDomain,port} from '../../config/config'
import './myPermission.less'

@connect(
  state => state,
  { onCheckTodayPlan }
)
class MyPermission extends Component {
  constructor(props) {
    super(props);
    this.state = {
      setStateOnce: this.once(this.getData),
      checkedList: [],
      checkboxOption: []
    };
  }

  getData=() => {
    this.setState({
      checkboxOption: this.props.checkPlan.checkTodayPlan[0].missions.map(
        v => {
          return {
            value: v._id,
            label: v.missionName,
            desc: `${v.missionDetails}
${v.startTime} ~ ${v.endTime}`,
            finished:v.finished
          };
        }
      ),
      checkedList: this.props.checkPlan.checkTodayPlan[0].missions
        .map(v => {
          return v.finished&&v.finished===true? v._id : "";
        })
        .filter(v => {
          return !(v === "");
        })
    });
  }

  once(func,run) {
    var ran, result;

    return function() {
      if (ran&&!run) {
        return result;
      }
      ran = true;
      result = func.apply(this, arguments);

      // clear the `func` variable so the function may be garbage collected
      func = null;
      return result;
    };
  }

  componentDidUpdate(prevProps) {
    if(!Immutable.is(this.props.checkPlan.checkTodayPlan,prevProps.checkPlan.checkTodayPlan))
    {
      this.once(this.getData,true)();
    }
    else{
      this.props.checkPlan.checkTodayPlan &&
      this.props.checkPlan.checkTodayPlan.length > 0
        ? this.state.setStateOnce()
        : null;
    }
  }

  updateMissions(finished){
    Taro.atMessage({
      message: finished?(this.props.user.specialWords.length===0?"取消完成":this.props.user.specialWords[6][1]):(this.props.user.specialWords.length===0?"任务完成":this.props.user.specialWords[6][0]),
      type: "info"
    });
    let today = new Date(),
    data = {
      user: this.props.user.openid,
      days: [
        dayjs(
          `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`
        ).format("YYYY-MM-DD")
      ]
    };
    this.props.onCheckTodayPlan(data,()=>{
      this.setState((prevState,props)=>{
        return {
          checkboxOption: props.checkPlan.checkTodayPlan[0].missions.map(
            v => {
              return {
                value: v._id,
                label: v.missionName,
                desc: `${v.missionDetails}
${v.startTime} ~ ${v.endTime}`,
                finished:v.finished
              };
            }
          ),
          checkedList: props.checkPlan.checkTodayPlan[0].missions
            .map(v => {
              return v.finished&&v.finished===true? v._id : "";
            })
            .filter(v => {
              return !(v === "");
            })
        }
      })
    })
  }

  handleChange(value,finished) {
    Taro.showToast({
      title: finished?"正在取消":"正在完成",
      icon:'loading',
      mask:true
  }).then(()=>{
      Taro.request({
          url: `${serverDomain}:${port}/plan/changeMissionState`,
          method: "POST",
          data: {missionIds:value,planId:this.props.checkPlan.checkTodayPlan[0]._id},
          success: res => {
            if(res.data.code==0)
            {
             this.updateMissions(finished);
            }
            else{
              Taro.atMessage({
                message: "服务器出错",
                type: "error",
                duration:3000
              });
            }
          },
          fail: () => {
            Taro.atMessage({
              message: "服务器出错",
              type: "error",
              duration:3000
            });
          },
          complete:Taro.hideToast
      })
  })
  }

  handleSwipeClick=(option)=>{
    Taro.showToast({
      title:'正在操作',
      icon:'loading',
      mask:true
  }).then(()=>{
    Taro.request({
      url: `${serverDomain}:${port}/plan/deleteMissions`,
      method: "POST",
      data: {missionIds:option.value,planId:this.props.checkPlan.checkTodayPlan[0]._id},
      success:(res)=>{
        if(res.data.code==0)
        {
          this.updateMissions();
        }
        else{
          Taro.atMessage({
            message: "服务器出错",
            type: "error",
            duration:3000
          });
        }
      },
      fail:()=>{
        Taro.atMessage({
          message: "服务器出错",
          type: "error",
          duration:3000
        });
      },
      complete:Taro.hideToast
    })
  })
  }

  render() {
   
    const allItems = this.props.checkPlan.checkTodayPlan;
    const hasData = allItems && allItems[0] !== null&&allItems[0].missions.length!==0;
    const finishedAll=this.state.checkedList.length===this.state.checkboxOption.length;
    const showAtProgress=!(this.state.checkboxOption.length===0);
    return (
      <View>
        {
          showAtProgress?(<AtProgress percent={Math.round(this.state.checkedList.length/this.state.checkboxOption.length*100)} status={finishedAll?'success':'progress'} color={finishedAll?'#13CE66':'#78A4F4'} />):null
        }
        {hasData?this.state.checkboxOption.map((v, i) => {
          return (
            <AtSwipeAction
              key={i}
              onClick={val=>{this.handleSwipeClick(v)}}
              options={[
                {
                  text: "删除",
                  style: {
                    backgroundColor: "#FF4949"
                  }
                }
              ]}
            >
              <AtCheckbox
                options={[v]}
                selectedList={this.state.checkedList.some((item)=>{
                  return item===v.value
                })?[v.value]:[]}
                onChange={()=>{
                  this.handleChange.bind(this)([v.value],v.finished)
                }}
              />
            </AtSwipeAction>
          );
        }):<View className='no-plan'>暂无计划，快去制定计划吧！</View>
      }
      </View>
    );
  }
}

export default MyPermission;
